import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'


// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: '/jdApis', // url = base url + request url
  // 临时修改2024-01-05 19:54:00
  withCredentials: false, // send cookies when cross-domain requests
  timeout: 1000000// request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // headers 传token
    config.headers['Lang'] = store.getters.language=="zh"?'zh_CN':'ko_KR'
    if (store.getters.token) {
      config.headers['Token'] = getToken()?getToken():''
    }
    return config
  },
  error => {
    // 报错信息
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  response => {
    const res = response.data
    if (res.code == 0  || res.code == 200) {
      return res
    } else {
      // code!=0 接扣报错
      if(typeof res =='string'){
        return res
      }
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.msg || 'Error'))
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
    })
    store.dispatch('user/resetToken').then(() => {
      location.reload()
    })
    return Promise.reject(error.message)
  }
)

export default service
